<?php

declare(strict_types=1);

namespace App\Model;


use App\Utils\MemcacheClient;

/**
 * @property int $id ID
 * @property string $keyword
 * @property int $type 类型：1-字符，2-正则
 * @property int $sub_type 0=>昵称 1=》私信
 */
class Filtration extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'tb_filtration';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'type' => 'integer', 'sub_type' => 'integer'];


    // 非法关键词检测
    public function isExistIllega($content, $sub_type = 0)
    {
        // 关键过滤是否开启
        $scriptFiltration = Setting::value('script_filtration');
        if ($scriptFiltration != 1) {
            return false; // 未开启，直接返回合法
        }

        $keyword = MemcacheClient::getInstance()->get('FilterAction_type_' . $sub_type);
        if (empty($keyword)) {
            $keyword = self::query()->where('type', 1)->where('sub_type', $sub_type)->pluck('keyword', 'id')->toArray();
            MemcacheClient::getInstance()->set('FilterAction_type_' . $sub_type, $keyword, 30 * 10);
        }
        if (!empty($keyword)) {
            foreach ($keyword as $val) {
                $k_word = explode(',', $val);
                foreach ($k_word as $v) {
                    if (!empty($v) && str_contains($content, $v)) {
                        return true; // 含有非法关键词
                    }
                }
            }
        }
        return false; //合法
    }

    // 非法关键词检测
    public function isExistIllegaV($content, $sub_type = 0)
    {
        // 关键过滤是否开启
        $scriptFiltration = Setting::value('script_filtration');
        if ($scriptFiltration != 1) {
            return false; // 未开启，直接返回合法
        }

        $regex = MemcacheClient::getInstance()->get('FilterAction_type_' . $sub_type);
        if (empty($regex)) {
            $keyword = self::query()->where('type', 1)->where('sub_type', $sub_type)->pluck('keyword', 'id')->toArray();
            $k1 = array_merge(...array_map(function ($val) {
                return explode(',', $val);
            }, $keyword));
            $k3 = array_map(function ($val) {
                return preg_quote(str_replace(',', '|', $val), '/');
            }, array_unique($k1));
            $regex = '/\b' . implode('|', $k3) . '\b/i';
            MemcacheClient::getInstance()->set('FilterAction_type_' . $sub_type, $regex, 30);
        }

        if (preg_match($regex, $content)) {
            return true; // 含有非法关键词
        }
        return false; //合法
    }


}
